package com.china08.yxyapi.api.comm.bigfileupload;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsTemp;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.db.YxyLessonsTempRepository;

@CrossOrigin
@RestController
public class BigFileDelTempController extends YxyApiBaseController {

    @Autowired
    YxyLessonsTempRepository tempRepository;

    @Value("${weike.storage.upload.video}")
    private String uploadBasePath;

    @RequestMapping(value = "/api_yw/comm/bigfile/delete/temp", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void process(@RequestBody ReqModel model) throws Exception {
        String md5 = model.md5;

        // 临时目录，为转码视频目录
        String path = uploadBasePath + "/temp/" + md5;

        long l1 = System.currentTimeMillis();
        // 删除临时保存的数据,删除两天前的数据
        try {
            Date date = new Date();
            // 向后推两天
            long time = 1000 * 60 * 60 * 24 * 2;
            date.setTime(date.getTime() - time);
            List<YxyLessonsTemp> temps = tempRepository.findByMd5AndCreatedDateLessThanEqual(md5, date);
            if (temps.size() > 0) {
                tempRepository.deleteInBatch(temps);
            }

            // 再次获取
            temps = tempRepository.findByMd5(md5);
            if (temps.size() == 0) {
                // 删除临时目录
                try {
                    FileUtils.deleteDirectory(new File(path));
                    System.out.println("删除临时目录成功");
                } catch (IOException e) {
                    System.out.println("删除临时目录异常");
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            System.out.println("删除临时保存的数据异常");
        }
        System.out.println("删除临时数据用时：" + (System.currentTimeMillis() - l1));
    }

    public static class ReqModel extends YxyApiReqModel {
        public String md5;
    }
}
